##########################################
#
# Copyright 2008 David B. Spadea
# All rights reserved
#
# http://www.spadea.net
#
# This program and all supporting code  
# is released under the terms of the 
# GNU General Public License version 3.
#
##########################################

package BatchTools::FileGen;

use strict;
use warnings;

use Data::Dumper;

use BatchTools::Database;

our $DB; # Batchtools database. 

sub new
{
	my $class = shift;
	my %opts = @_;

	$DB = BatchTools::Database->new
		or return undef;

	$DB->do("set search_path = filegen, cal, pg_catalog");

	my $self = {};

	$$self{Name} = $opts{Name}; # Value of Files.name 

	$self = bless ($self, $class);

	$self->_load_filedef
		or return undef;
	
	$self->_load_callbacks
		or return undef;
	
	return $self;
}

sub _load_callbacks
{
	my $self = shift;

	my $format = ucfirst $$self{FileDef}{file_format};
	my $output = ucfirst $$self{FileDef}{file_output};

	my $class = _load_module("format", $format);
	$$self{Formatter} = \&{ $class . "::format" };

	$class = _load_module("output", $output);
	$$self{Output} = \&{ $class . "::output" };

	return 1;
}

sub _load_module
{
	my $type = ucfirst shift;
	my $module = ucfirst shift;

	my $class = "BatchTools::FileGen::" . $type . "::" . $module;

	eval "require $class";

	return $class;
}

sub _load_filedef
{
	my $self = shift;

	my $sql = <<SQL;

	select 	  rep.name as report_name
		, rep.source as report_source
		, rep.source_type as report_source_type
		, file.name as file_name
		, file.format as file_format
		, file.output as file_output
	from files file
		inner join reports rep
			on file.src_report_id = rep.id
	where file.name = ?

SQL

	my $sth = $DB->prepare($sql)
		or die ($DBI::errstr);
	
	$sth->execute( $$self{Name} )
		or die ($DBI::errstr);
	
	$$self{FileDef} = $sth->fetchrow_hashref;

	$sth->finish;

	return 1;
}

sub execute
{
	my $self = shift;

	my $filedef = $$self{FileDef}
		or die ("FileDef was not set! What happened?!");
	
	my $sql;

	if ($$filedef{report_source_type} eq 'rowsource')
	{
		$sql = "select * from " . $$filedef{report_source};
	}
	elsif ($$filedef{report_source_type} eq 'query')
	{
		$sql = $$filedef{report_source};
	}
	
	# This eventually needs to be able to connect to 
	# Sybase/Oracle/etc, so we'd need to have some 
	# additional logic here. For now just assume it's coming 
	# out of the batchtools database. 
	
	my $sth = $DB->prepare($sql)
		or die($DBI::errstr);

	$sth->execute
		or die($DBI::errstr);

	$self->_output($sth);

	$sth->finish;
}

sub _output
{
	my $self = shift;
	my $sth = shift;

	my $output = $$self{Output};
	my $formatter = $$self{Formatter};

	my $filedef = $$self{FileDef};

	if ($$filedef{use_col_headers})
	{
		$output->( $formatter->( $sth->{NAME}, $sth->{NAME} ) );
	}

	while (my $row = $sth->fetchrow_arrayref)
	{
		$output->( $formatter->( $sth->{NAME}, $row ) );
	}

	return 1;
}

1;
